import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:mall/core/models/news_query.dart';
import 'package:mall/core/models/store_index.dart';
import 'package:mall/core/services/api.dart';
import 'package:mall/core/providers/view_model.dart';

class NewsQueryModel extends ViewModel {
  final Api api;
  final int storeId;
  final String linkType;
  String _queryKey = ''; // 非null默认值
  final List<Link> _list = [];
  String _errorMessage;
  NewsQuery _newsQuery;

  NewsQueryModel(this.api, this.storeId, this.linkType) : super();

  set queryKey(String value) {
    debugPrint('$this set queryKey = $value');
    if (_queryKey != value) {
      _queryKey = value;
      _initData();
    }
  }

  List<Link> get list => _list;

  String get errorMessage => _errorMessage;

  NewsQuery get newsQuery => _newsQuery;

  Future<ViewState> _initData() async {
    viewState = ViewState.busy;
    try {
      var params = <String, dynamic>{};
      params['storeId'] = storeId;
      params['linkType'] = linkType;
      params['queryKey'] = _queryKey;
      params['pageIndex'] = 0;
      _newsQuery = await api.newsQuery(params);
      _list.clear();
      _list.addAll(_newsQuery.newsList);
      if (_list.isEmpty) {
        throw '暂无数据';
      }
      viewState = ViewState.success;
    } catch (e) {
      _errorMessage = e is DioError ? e.message : e.toString();
      viewState = ViewState.error;
    }
    return viewState;
  }

  Future<ViewState> loadData() async {
    try {
      var params = <String, dynamic>{};
      params['storeId'] = storeId;
      params['linkType'] = linkType;
      params['queryKey'] = _queryKey;
      params['pageIndex'] = _list.length ~/ 10;
      _newsQuery = await api.newsQuery(params);
      _list.addAll(_newsQuery.newsList);
      viewState = ViewState.success;
    } catch (e) {}
    return viewState;
  }
}
